<?php
namespace app\common\job;

use think\queue\Job;

/**
 * 下载产品图片
 * @author King
 *
 */
class DownloadPic{

	protected $logName = 'downloadPic';
	protected $skuId = 0;

	public function fire(Job $job, $data){

		if ($job->attempts() > 3) {
			$this->failed($data);
		}
		$this->logName = 'downloadPic';
		$this->skuId = 0;

		try {
			$this->skuId = $data;
			if (empty($this->skuId)) throw new \Exception("产品ID数据解析异常");

			$skuInfo = db('sku')->where('id', $this->skuId)->findOrEmpty();
			$error = '';
			$pic = downloadPic($skuInfo['ori_pic'], $error);
			if ($pic != '') {
				db('sku')->where('id', $this->skuId)->update(['pic' => $pic]);
				cache(SKU_PIC.$skuInfo['sku'], $pic);

				$msg = "产品{$this->skuId}图片下载成功";

				if($skuInfo['pic'] != '') {
					// 删除旧图片（http://www.020mimo.com/upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg）
					$oldPicPath = parse_url($skuInfo['pic'], PHP_URL_PATH); // /upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg
					$oldPic = env('root_path').'public'.$oldPicPath;
					if (file_exists($oldPic)) {
						if (unlink($oldPic)) $msg = $msg."，成功删除旧图片：".$oldPicPath;
						else $msg = $msg."，删除旧图片失败：".$oldPicPath;
					} else $msg = $msg."，旧图片不存在：".$oldPicPath;
				} else $msg = $msg."，无旧图片";

			} else {
				$msg = "产品{$this->skuId}图片下载失败，" . $error;
			}

			consoleLog($msg);
			addLog($msg, $this->logName);
		} catch (\Exception $e) {
			consoleLog($e->getMessage());
			addLog($e->getMessage(), $this->logName);
		}

		$job->delete();
	}

	public function failed($data){
		$msg = "产品{$this->skuId}执行多次失败";
		consoleLog($msg);
		addLog($msg, $this->logName);
	}

}